

package com.upc.feedish;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.upc.feedish.utils.DataBaseController;
import com.upc.feedish.utils.HuaweiCloudTools;
import com.upc.feedish.utils.MyBroadcastReceiver;

import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity  {

    private Intent intentS ;
    private EditText text_password;
    private EditText text_username;
    MyBroadcastReceiver br;
    PopupWindow popupWindow;
    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //返回一个MsgService对象
            InternetService internetService = ((InternetService.MsgBinder) service).getService();
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        intentS = new Intent(MainActivity.this,InternetService.class);
//        bindService(intentS, conn, Context.BIND_AUTO_CREATE);



        Button button_register = findViewById(R.id.button_showRegister);
        Button button_login = findViewById(R.id.button_login);
        text_password=findViewById(R.id.editTextTextPassword);
        text_username=findViewById(R.id.editTextTextPersonName);

        Toast toastWrongPass = Toast.makeText(MainActivity.this, "Wrong Password!",Toast.LENGTH_SHORT);
        Toast toastInternetError = Toast.makeText(MainActivity.this, "Internet Error!",Toast.LENGTH_SHORT);
        Toast toastNull = Toast.makeText(MainActivity.this, "请输入用户名或密码",Toast.LENGTH_SHORT);
        Toast toastNoSuchUsername = Toast.makeText(MainActivity.this, "用户名错误",Toast.LENGTH_SHORT);

        SharedPreferences sp = getSharedPreferences("data",MODE_PRIVATE);
        String localUsername= sp.getString("username","");
        text_username.setText(localUsername);
        String localPassword=sp.getString(text_username.getText().toString(),"");
        text_password.setText(localPassword);


        popupWindow = new PopupWindow();
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setContentView(LayoutInflater.from(this).inflate(R.layout.popup,null));
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(false);
        popupWindow.setTouchable(true);

         br=new MyBroadcastReceiver(){
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.i("broadcast","广播接收到了");
                super.onReceive(context, intent);
                int flg=intent.getIntExtra("flg",0);
                String token=intent.getStringExtra("token");
                if(flg==-1){
                    toastNoSuchUsername.show();
                    popupWindow.dismiss();
                }
                else if(flg==-500){
                    toastInternetError.show();
                    popupWindow.dismiss();
                }
                else if(flg==100){
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("username",text_username.getText().toString());
                    editor.putString(text_username.getText().toString(), text_password.getText().toString());
                    editor.putString("token",token);
                    editor.apply();
                    popupWindow.dismiss();
                    Intent intentL=new Intent(MainActivity.this,BarActivity.class);
                    intentL.putExtra("token",token);
                    savePicOnline(text_username.getText().toString(),token);
                    startActivity(intentL);
//                    unbindService(conn);
                    stopService(new Intent(MainActivity.this,InternetService.class));
                    finish();
                }
                else {
                    toastWrongPass.show();
                    popupWindow.dismiss();
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.upc.learning.RECEIVER");
        registerReceiver(br, intentFilter);


        button_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER,0,0);
                if(text_password.getText().toString().equals("")||text_username.getText().toString().equals("")){
                    toastNull.show();
                }
                else{
                    intentS.putExtra("username",text_username.getText().toString());
                    intentS.putExtra("password",text_password.getText().toString());
                    startService(intentS);
//                    internetService.isLogin(text_username.getText().toString(),text_password.getText().toString());
                }
            }
        });


        button_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentR=new Intent(MainActivity.this,RegisterActivity.class);
                startActivityForResult(intentR,1);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1&&resultCode == 1){
            String newUsername= data.getStringExtra("username"); //获取回传的数据
            String newPassword= data.getStringExtra("password"); //获取回传的数据
            text_username.setText(newUsername);
            text_password.setText(newPassword);
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(intentS);
        unregisterReceiver(br);
    }


    public void savePicOnline(String name,String token){
        new Thread(new Runnable() {
            @Override
            public void run() {
                DataBaseController dataBaseController=new DataBaseController();
                byte[] bytes=dataBaseController.getFile(token,name);
                String filename = name + ".jpg";
                try (FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE)) {
                    fos.write(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


}